﻿using GiteePlugin.Configuration;
using GiteePlugin.Core.Auth;
using Microsoft.Extensions.Options;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
using System.Web;

namespace GiteePlugin.Core
{
    public class GiteeAuthHandler : DelegatingHandler
    {
        private readonly IGiteeAuthProvider _authService;

        public GiteeAuthHandler(IGiteeAuthProvider authService)
        {
            _authService = authService;
        }

        protected override async Task<HttpResponseMessage> SendAsync(
            HttpRequestMessage request,
            CancellationToken cancellationToken)
        {
            // Gitee要求access_token放在query参数
            var accessToken = await _authService.GetAccessTokenAsync("code");
            var uriBuilder = new UriBuilder(request.RequestUri!);
            var query = HttpUtility.ParseQueryString(uriBuilder.Query);
            query["access_token"] = accessToken;
            uriBuilder.Query = query.ToString();
            request.RequestUri = uriBuilder.Uri;

            return await base.SendAsync(request, cancellationToken);
        }
    }
}
